<template>
  <div class="dashboard">
    <el-row :gutter="20">
      <el-col :span="6">
        <div class="tree-panel">
          <el-input
            placeholder="搜索设备/工程"
            v-model="filterText"
            clearable
          />
          <el-tree
            class="filter-tree"
            :data="treeData"
            :props="defaultProps"
            :filter-node-method="filterNode"
            @node-click="handleNodeClick"
            ref="tree"
          />
        </div>
      </el-col>

      <el-col :span="18">
        <div class="data-panel" v-if="params.device_id">
          <el-card shadow="hover">
            <div class="search-bar">
              <el-date-picker
                v-model="dateRange"
                type="datetimerange"
                range-separator="至"
                start-placeholder="开始时间"
                end-placeholder="结束时间"
                value-format="yyyy-MM-dd HH:mm:ss"
              />
              <el-button type="primary" @click="fetchData">查询</el-button>
            </div>

            <el-table :data="monitorData" style="width: 100%" border>
              <el-table-column prop="insert_time" label="日期" align="center">
                <template slot-scope="scope">
                  {{ formatDate(scope.row.insert_time) }}
                </template>
              </el-table-column>
              <el-table-column prop="tsp" label="tsp" align="center" />
              <el-table-column prop="pm10" label="pm10" align="center" />
              <el-table-column prop="pm25" label="pm2.5" align="center" />
              <el-table-column prop="temperature" label="温度" align="center" />
              <el-table-column prop="humidity" label="湿度" align="center" />
              <el-table-column prop="wind_direction" label="风向" align="center" />
              <el-table-column prop="wind_speed" label="风速" align="center" />
            </el-table>

            <div style="margin-top: 20px; text-align: center;">
              <el-pagination
                @current-change="handlePageChange"
                :current-page="Number(params.page)"
                :page-size="Number(params.pageSize)"
                :total="total"
                layout="prev, pager, next"
                background
              />
            </div>
          </el-card>
        </div>

        <div v-else class="no-data">请选择设备进行查看</div>
      </el-col>
    </el-row>
  </div>
</template>

<script>
import axios from 'axios'

export default {
  data() {
    return {
      filterText: '',
      treeData: [],
      monitorData: [],
      total: 0,
      dateRange: [], // 时间范围
      defaultProps: {
        children: 'children',
        label: 'name'
      },
      params: {
        device_id: '',
        engineer_id: '',
        page: 1,
        pageSize: 15
      },
      token: "Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VybmFtZSI6ImFkbWluIiwiaWF0IjoxNzQ1NjM3NDE5LCJleHAiOjE3NDYyNDIxMTl9.v7Lv-oVgFRAnecS2piBirRBCTgzsZZZodDBTZDqoC9A"
    }
  },
  watch: {
    filterText(val) {
      this.$refs.tree.filter(val)
    }
  },
  created() {
    console.log('History component created')
    this.fetchTree()
  },
  methods: {
    async fetchTree() {
      console.log('fetchTree called at:', new Date().toISOString())
      const res = await axios.get('http://101.37.38.67:7001/dashboard/findEngineerDeviceTree', {
        headers: {
          Authorization: this.token
        }
      })
      this.treeData = res.data.data || []
    },
    handleNodeClick(node) {
      if (!node.children) {
        this.params.device_id = node.id
        this.params.engineer_id = node.engineer_id
        this.params.page = 1
        this.fetchData()
      }
    },
    async fetchData() {
      const query = {
        page: String(this.params.page),
        pageSize: String(this.params.pageSize),
        device_id: String(this.params.device_id),
        engineer_id: String(this.params.engineer_id)
      }
      console.log("🚀 ~ fetchData ~ query:", query)

      if (this.dateRange.length === 2) {
        query.begin_time = this.dateRange[0]
        query.end_time = this.dateRange[1]
      }

      const res = await axios.get('http://101.37.38.67:7001/monitor/pageQuery', {
        params: query,
        headers: { Authorization: this.token }
      })
      console.log("🚀 ~ fetchData ~ res:", res)

      this.monitorData = res.data.data.list || []
      console.log("🚀 ~ fetchData ~ monitorData:", this.monitorData)
      this.total = res.data.data.total || 0
    },
    handlePageChange(val) {
      this.params.page = val
      this.fetchData()
    },
    filterNode(value, data) {
      if (!value) return true
      return data.name.includes(value)
    },
    formatDate(date) {
      if (!date) return ''
      const d = new Date(date)
      const year = d.getFullYear()
      const month = String(d.getMonth() + 1).padStart(2, '0')
      const day = String(d.getDate()).padStart(2, '0')
      const hour = String(d.getHours()).padStart(2, '0')
      const minute = String(d.getMinutes()).padStart(2, '0')
      const second = String(d.getSeconds()).padStart(2, '0')
      return `${year}-${month}-${day} ${hour}:${minute}:${second}`
    }
  }
}
</script>

<style scoped>
.dashboard {
  padding: 10px;
}
.tree-panel {
  border-right: 1px solid #eee;
  height: calc(100vh - 60px);
  overflow-y: auto;
}
.data-panel {
  padding: 10px;
}
.search-bar {
  margin-bottom: 10px;
  display: flex;
  gap: 10px;
  align-items: center;
}
.no-data {
  text-align: center;
  color: red;
  line-height: 300px;
}
</style>
